/**
 * 导出对话
 */
function currentDate() {
  const date = new Date();
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  return `${year}-${month}-${day}`;
}
export function exportChat(data: any) {
  const blob = new Blob([JSON.stringify(data)], { type: "application/json" });
  const url = URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = url;
  link.style.display = 'none';
  link.download = `chatHistory_${currentDate()}.json`;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

// 导入对话
export function importChat() {
  return new Promise((resolve) => {
    const el = document.createElement("input");
    el.type = "file";
    el.name = "file";
    el.accept = "application/json";
    el.style.display = "none";
    document.body.appendChild(el);

    // 选中
    el.addEventListener("change", (e: any) => {
      if (e.target && e.target.files && e.target.files.length) {
        const file = e.target.files[0];
        const reader = new FileReader();
        reader.onload = function (e: any) {
          const result = JSON.parse(e.target.result);
          resolve(result);
        };
        reader.readAsText(file);
      }
    });

    // 取消
    window.addEventListener("focus", () => {
      el.remove();
    }, { once: true });

    // 执行点击
    el.dispatchEvent(new MouseEvent("click"));
  });
}
